var displayRate = 1; // 方案屏幕缩放比例
var schemeWidth = -1, schemeHeight = -1; // 方案屏幕宽和高
var materialWidth = -1, materialHeight = -1;// 素材宽和高
var schemeQuestions = null; // 方案问卷信息

var gridmapDataList = null; // 网格图当前绘制数据集
var aoiDataList = null; // 兴趣区当前绘制数据集
var selectGridMapKey = null; // 选中的网格内容

var aoiGraphs_temp = new Array();// 绘制图形的临时集合
var schemeAoiGraphs = null; // AOI图形的集合
var modifyAoiIndex = -1; // 当前待编辑的AOI图形，在aoiDataList中的index,与schemeAoiGraphs的index一致

var drawTool = null;
var focusmapCanvas = null;
var routemapCanvas = null;
var gridmapCanvas = null;
var aoiCanvas = null;
var resultDataList = []; // 被试数据集
var split_sign = "_"; // 已选中结果分割标识

/** ************************* */
var playRouteFunction = null; // 轨迹图播放方法
var playPauseFlag = false; // 播放暂停标志
var playInterval = 200; // 播放间隔
var playProgressCurrentTime = 0; // 播放进度当前时间
var playProgressTotalTime = 0; // 播放进度总时间
var playOffsetTime = 0; // 素材播放偏移时间
/** ************************* */

var widgetWidthRecord = null; // 记录画布区域第一次的大小，便于后续固定
var colmainHeightRecord = null; // 记录col-main区域第一次的大小，便于后续固定

$(function () {
    /** 加载方案信息 */
    schemeWidth = $("#schemeWidth").val();
    schemeHeight = $("#schemeHeight").val();
    schemeQuestions = eval('(' + $("#schemeQuestions").val() + ')'); // 方案所有问卷信息(含属性)
    loadResultAttribute(schemeQuestions); // 加载结果的所有属性

    loadAoiGraphs();

    /** 先调整下高度,保证异步调用AJAX正常 */
    sliderH();

    /** 加载显示素材 */
    var material = {
        code: $("#materialCode").val(),
        type: $("#materialType").val()
    };

    selectMaterialHook(material);

    /** 根据类型判断是否显示结果颜色 */
    var type = $("#analysisType").val();
    if (type == AnalysisTypeEnum.HEATMAP || type == AnalysisTypeEnum.FOCUSMAP || type == AnalysisTypeEnum.GRIDMAP) {
        // $("#tr_th_result_color").hide();
    }

    /** 根据类型判断是否显示颜色示例条 */
    if (type == AnalysisTypeEnum.GRIDMAP) {
        $("#color_example").show();
    } else {
        $("#color_example").hide();
    }

    /** 参数选择区域 */
    // configListSet();
    /** 根据分析类型+素材类型判断是否显示 动态播放区域 */
    // playAreaSet();
    /** 设置窗口大小变化时重新调整函数 */
    $(window).resize(function () {
        // sliderH();
    });

    /** 设置选择素材函数 */
    $("#testObject").click(function () {
        ownClear(); // 选择前先清除渲染
        chooseMaterial();
    });

    /** 基于已选中的结果直接绘制 */
    // ownDrawByAlreadyCheckboxs();
    /** 绑定浮动显示 */
    bindTopic();

    /** 绑定参数解释 */
    bindConfigExplain();

    /** 轨迹图播放进度条初始化 */
    $("#progressbar").progressbar({
        value: 0,
        change: function () {
            changeProgressbar();
        },
        complete: function () {
        }
    });
    ownPlayRouteMap_progress();

    /** 初始测评结果区域鼠标右键菜单 */
    initDataListRightMenu();

});

/**
 * 改变结果数据
 */
function changeProgressbar() {
    $("#progressLabel").text($("#playProgress").val());
}

/**
 * 根据参数相关关系，设置参数列表
 */
function configListSet() {
    var type = $("#analysisType").val();

    if (type == AnalysisTypeEnum.ROUTEMAP) {
        $("#configBody").find("tr").each(function () {
            $(this).show();
        }); // 先全部显示

        if (parseInt($("#cfg_route_data_source_type").val()) == 1) { // 数据来源为注视点时
            if (parseInt($("#cfg_route_radius_type").val()) == 1) { // 按注视时间来确定圆圈大小时
                $("#configBody").find("tr").eq(3).hide(); //
            } else {
                $("#configBody").find("tr").eq(2).hide();
            }
        } else {
            $("#configBody").find("tr").eq(1).hide();
            $("#configBody").find("tr").eq(2).hide();
            $("#configBody").find("tr").eq(3).hide();
            // $("#configBody").find("tr").eq(5).hide();
        }

        $("#configBody").find("tr").eq(5).hide(); // 隐藏视频播放速率
        if ($("#materialType").val() == MaterialTypeEnum.RECORD) {
            $("#configBody").find("tr").eq(5).show(); // 当素材类型是视频时，才显示视频播放速率
        }
    } else if (type == AnalysisTypeEnum.HEATMAP) {
        $("#configBody").find("tr").eq(1).hide(); // 隐藏视频播放速率
        if ($("#materialType").val() == MaterialTypeEnum.RECORD) {
            $("#configBody").find("tr").eq(1).show(); // 当素材类型是视频时，才显示视频播放速率
        }
    } else if (type == AnalysisTypeEnum.FOCUSMAP) {
        $("#configBody").find("tr").eq(1).hide(); // 隐藏视频播放速率
        if ($("#materialType").val() == MaterialTypeEnum.RECORD) {
            $("#configBody").find("tr").eq(1).show(); // 当素材类型是视频时，才显示视频播放速率
        }
    } else if (type == AnalysisTypeEnum.AOI) {
        // 需要重新定义AOI绘制时的颜色选择，使其更直观的呈现
        var colorObj = $("#configBody").find("tr").eq(0).find("td").eq(1);
        initAoiDrawColors(colorObj);
    }
}

/** 根据分析类型+素材类型判断是否显示 动态播放区域 */
function playAreaSet() {
    var type = $("#analysisType").val();

    $("#playArea").hide();
    $("#playArea_video").hide();
    if ($("#materialType").val() == MaterialTypeEnum.RECORD || $("#materialType").val() == MaterialTypeEnum.VIDEO) {
        $("#playArea_video").show();
    } else {
        if (type == AnalysisTypeEnum.ROUTEMAP) {
            $("#playArea").show();
        }
    }
}

/**
 * 保存已选中的结果checkbox
 *
 * @param checkboxs
 * @param theChangeCheckBox
 *            当前改变状态的checkbox
 */
function saveAlreadyCheckboxs(theChangeCheckBox) {
    var boxArray = getAlreadyCheck(true);
    if (boxArray.length <= 0) {
        setAlreadyValue("");
    } else {
        var value = boxArray.eq(0).val();
        for (var i = 1; i < boxArray.length; i++) {
            value += split_sign + boxArray.eq(i).val();
        }
        setAlreadyValue(value);
    }
}

/**
 * 基于已选中的结果直接绘制
 */
function ownDrawByAlreadyCheckboxs() {
    //1、默认最后一个checkbox内容, 获取当前应该初始化的值
    var box = getAlreadyValue();
    if (!box) {
        // 默认选中最后一个box
        var checkBox = getAlreadyCheck();
        if (checkBox && checkBox.length > 0) {
            setAlreadyValue($(checkBox[checkBox.length - 1]).val());
        }
    }
    var boxArray = getAlreadyValue().split(split_sign);
    if (boxArray.length > 0) {
        getAlreadyCheck().each(function () {
            var me = $(this);
            for (var i = 0; i < boxArray.length; i++) {
                if (me.val() == boxArray[i]) {
                    me.attr('checked', true);
                    break;
                }
            }
        });
        ownDraw(); // 绘制
    }
}

/**
 * 清理最新的选中状态
 * @param hasForce
 */
function clearAlreadyCheck(hasForce) {
    if (hasForce) {
        getAlreadyCheck().each(function () {
            $(this).attr("checked", hasForce);
        });
        saveAlreadyCheckboxs(null);
    }
}

/**
 * 选择所有结果,并且绘制
 */
function ownSelectAllAndDraw() {
    clearAlreadyCheck(true);
    ownDraw();
}

/**
 * 清除当前绘制内容
 */
function ownClear() {
    clearAlreadyCheck(false);
    if ($("#materialType").val() == MaterialTypeEnum.RECORD) { // 素材类型是录制
        ownVideoClear(); // 参见analysis_core_supply.js中
        return;
    }
    var type = $("#analysisType").val();
    if (type == AnalysisTypeEnum.HEATMAP) {
        ownClearHeatmap();
    } else if (type == AnalysisTypeEnum.ROUTEMAP) {
        ownClearRoutemap();
    } else if (type == AnalysisTypeEnum.FOCUSMAP) {
        ownClearFocusmap();
    } else if (type == AnalysisTypeEnum.GRIDMAP) {
        ownClearGridmap();
    } else if (type == AnalysisTypeEnum.AOI) {
        ownClearAoi();
    }
}

/**
 * 清除绘制的热点图
 */
function ownClearHeatmap() {
    if (drawTool) {
        drawTool.clearHeatMap();
        drawTool = null;
    }
}

/**
 * 清除绘制的焦点图
 */
function ownClearFocusmap() {
    if (focusmapCanvas != null) {
        $("#myCanvas").remove();
        focusmapCanvas = null;
    }
}

/**
 * 清除绘制的轨迹图
 */
function ownClearRoutemap() {
    if (routemapCanvas != null) {
        $("#myCanvas").remove();
        routemapCanvas = null;
    }
}

/**
 * 清除绘制的网格图
 */
function ownClearGridmap() {
    if (gridmapCanvas != null) {
        $("#myCanvas").remove();
        gridmapCanvas = null;
    }
}

/**
 * 清除绘制的兴趣区
 */
function ownClearAoi() {
    if (aoiCanvas != null) {
        $("#myCanvas").remove();
        aoiCanvas = null;
    }
}

/**
 * 绘制图形
 *
 * @param checkboxs
 */
function ownDraw() {
    if ($("#materialType").val() == MaterialTypeEnum.RECORD) { // 素材类型是录制
        ownVideoDraw(); // 参见analysis_core_supply.js中
        return;
    }

    var boxArray = getAlreadyCheck(true); // 根据已选中的checkbox绘制
    ownPlayRouteMap_stop(false); // 绘制之前做个保护:停止静态轨迹图播放(经测试发现：轨迹图播放时，不停止点击其它图形会绘制失败)
    var type = $("#analysisType").val();
    if (type == AnalysisTypeEnum.HEATMAP) {
        ownDrawHeatmap(boxArray);
    } else if (type == AnalysisTypeEnum.ROUTEMAP) {
        ownDrawRoutemap(boxArray);
    } else if (type == AnalysisTypeEnum.FOCUSMAP) {
        ownDrawFocusmap(boxArray);
    } else if (type == AnalysisTypeEnum.GRIDMAP) {
        ownDrawGridmap(boxArray);
    } else if (type == AnalysisTypeEnum.AOI) {
        ownDrawAoi(boxArray);
    }
}

/**
 * 绘制热点图
 *
 * @param checkboxs
 *            选中的被试
 */
function ownDrawHeatmap(checkboxs) {
    ownClearHeatmap();
    if (checkboxs.length <= 0) {
        return;
    }
    var muliPoints = new Array();
    for (var i = 0; i < checkboxs.length; i++) {
        muliPoints.push(resultDataList[checkboxs.eq(i).val()].fixData);
    }
    var tools = eyeTools.create({
        "element": $("#displayArea"),
        datapoints: muliPoints,
        baseRadius: parseInt($("#cfg_heat_radius").val()) * displayRate,
        worker: checkboxs.length
    });
    drawTool = tools;
    tools.multDrawHeatMap();
}

/**
 * 绘制焦点图
 *
 * @param checkboxs
 *            选中的被试
 */
function ownDrawFocusmap(checkboxs) {
    ownClearFocusmap();
    addFocusCanvas();
    focusmapCanvas = $("#myCanvas");

    if (checkboxs.length <= 0) {
        return;
    }

    var muliPoints = new Array();
    for (var i = 0; i < checkboxs.length; i++) {
        muliPoints.push(resultDataList[checkboxs.eq(i).val()].fixData);
    }

    var tools = eyeTools.create({
        "element": $("#myCanvas"),
        datapoints: muliPoints,
        baseRadius: parseInt($("#cfg_focus_radius").val()) * displayRate,
        worker: checkboxs.length
    });

    tools.multDrawFocusMap();
}

/**
 * 绘制轨迹图
 *
 * @param checkboxs
 *            选中的被试
 */
function ownDrawRoutemap(checkboxs) {
    ownClearRoutemap();

    ownPlayRouteMap_play(checkboxs.length); // 设置播放按钮

    if (checkboxs.length <= 0) {
        return;
    }

    addRouteCanvas();
    routemapCanvas = $("#myCanvas");

    var allColors = ["#7cff66", "#ffbc66", "#66ffdd", "#ff6666", "#66e0ff", "#ff8a66", "#66aaff", "#667fff", "#a066ff", "#fa66ff"];
    var muliPoints = new Array();
    var colors = new Array();
    for (var i = 0; i < checkboxs.length; i++) {
        if (parseInt($("#cfg_route_data_source_type").val()) == 1) { // 轨迹图数据来源：1表示注视点,2表示原始
            muliPoints.push(resultDataList[checkboxs.eq(i).val()].fixData);
        } else {
            muliPoints.push(resultDataList[checkboxs.eq(i).val()].rawData);
        }
        colors.push(allColors[checkboxs.eq(i).val() % 10]); // 目前10个颜色,故取10的余数
    }

    // console.log("选中的参数", muliPoints);

    var tools = eyeTools.create({
        "element": $("#myCanvas"),
        datapoints: muliPoints,
        colors: colors,
        routeRadiusType: parseInt($("#cfg_route_radius_type").val()),
        baseRadius: parseInt($("#cfg_route_radius").val()) * displayRate,
        routeAlterableRadius: parseInt($("#cfg_route_alterable_radius").val()) * displayRate,
        routeMapDataSourceType: parseInt($("#cfg_route_data_source_type").val()),
        diaphaneity: $("#cfg_route_diaphaneity").val(),
        worker: checkboxs.length
    });

    tools.multDrawRouteMap();
}

/**
 * 绘制网格图
 *
 * @param checkboxs
 *            选中的被试
 */
function ownDrawGridmap(checkboxs) {
    ownClearGridmap();
    addGridCanvas();
    gridmapCanvas = $("#myCanvas");

    if (checkboxs.length <= 0) {
        return;
    }

    var colors = ["#adb5ff", "#427bfc", "#3f9a8e", "#0eca23", "#49f016", "#d0d010", "#f8d010", "#f89f10", "#f86e10", "#f82810", "#cc1212", "#ae1111"];

    var muliPoints = new Array();
    for (var i = 0; i < checkboxs.length; i++) {
        // 调整数据模型内容
        var xt = resultDataList[checkboxs.eq(i).val()];
        var fixData = xt.fixData;
        if (fixData) {
            fixData.forEach(function (f) {
                f.base = {
                    code: xt.code,
                    name: xt.name
                };
            });
        }
        muliPoints.push(fixData);
    }

    var grid = eyeGrid.create({
        "element": $("#myCanvas"),
        datapoints: muliPoints,
        colors: colors,
        screenWidth: schemeWidth * displayRate,
        screenHeight: schemeHeight * displayRate,
        rows: parseInt($("#cfg_grid_row").val()),
        columns: parseInt($("#cfg_grid_column").val()),
        worker: checkboxs.length,
        showType: parseInt($("#cfg_grid_showtype").val())
    });

    gridmapDataList = grid.drawGridByFiaxtion();
}

/**
 * 绘制兴趣区
 *
 * @param checkboxs
 *            选中的被试
 */
function ownDrawAoi(checkboxs) {
    ownClearAoi();
    addAoiCanvas();
    aoiCanvas = $("#myCanvas");

    var isShowData = true; // AOI比较特殊，无论有无被试，都要画出来
    if (checkboxs.length <= 0) {
        isShowData = false;
        aoiDataList = null; // 清空之前已绘制的兴趣区数据集
    }

    var muliPoints = new Array();
    for (var i = 0; i < checkboxs.length; i++) {
        muliPoints.push(resultDataList[checkboxs.eq(i).val()].fixData);
    }

    var aoi = eyeAoi.create({
        "element": "myCanvas",
        datapoints: muliPoints,
        colors: $("#cfg_aoi_color").val(),
        diaphaneity: $("#cfg_aoi_diaphaneity").val(),
        worker: checkboxs.length,
        showType: parseInt($("#cfg_grid_showtype").val()),
        graphs: schemeAoiGraphs
    });

    aoiDataList = aoi.drawAoiByFiaxtion(isShowData);
    updateAoiGraphs();
    initAoiDrawButtonStyle();
}

/**
 * 动态播放轨迹图_准备
 */
function ownPlayRouteMap_prepare() {
    ownPlayRouteMap_stop(false); // 先停止播放
    playPauseFlag = false; // 设置播放暂停标志为false
    ownPlayRouteMap_progress((playProgressCurrentTime = 0)); // 播放进度条置为0
    ownClearRoutemap();
    addRouteCanvas();
    routemapCanvas = $("#myCanvas");

    var boxArray = getAlreadyCheck(true);
    if (boxArray.length <= 0) {
        return;
    }

    var tools = eyeTools.create({}); // 对象实例只初始化一次

    var allColors = ["#7cff66", "#ffbc66", "#66ffdd", "#ff6666", "#66e0ff", "#ff8a66", "#66aaff", "#667fff", "#a066ff", "#fa66ff"];
    var muliPoints = new Array();
    var colors = new Array();
    var playTimes = new Array(); // 播放基准时间
    var routeCurrentNumber = new Array(); // 当前帧轨迹圆圈中填充的数值

    for (var i = 0; i < boxArray.length; i++) {
        var points = resultDataList[boxArray.eq(i).val()].fixData;

        muliPoints.push(points); // 待播放数据
        colors.push(allColors[boxArray.eq(i).val() % 10]); // 目前10个颜色,故取10的余数
        playTimes.push({
            start: 0, // 第1帧开始时间为0
            end: playInterval, // 第1帧结束时间为播放速率对应的毫秒数
            finish: playProgressTotalTime
            // 整体结束时间为整个素材的播放时间
        }); // 初始播放基准时间
        routeCurrentNumber.push(1); // 初始起始数值
    }

    // 偏移量
    playOffsetTime = points[0].fixStart;

    // console.log("播放坐标", muliPoints, playTimes);

    playRouteFunction = setTimeout(function () {
        ownPlayRouteMap_realplay(tools, muliPoints, playTimes, colors, boxArray.length, routeCurrentNumber);
    }, 0);

    /** 按钮事件调整 */
    $("#playButton").unbind("click"); // 取消原绑定事件
    $("#playButton").bind("click", function () {
        ownPlayRouteMap_pause(); // 设置成暂停事件
    });
    $("#playButton").find("i").attr("class", "icon-play-pause");

    $("#stopButton").unbind("click");
    $("#stopButton").bind("click", function () {
        ownPlayRouteMap_stop(true);
    });
    $("#stopButton").find("i").attr("class", "icon-play-stop");// 停止按钮可以点击
}

/**
 * 动态播放轨迹图_实际播放
 *
 * @param tools
 * @param muliPoints
 * @param playTimes
 * @param colors
 * @param worker
 * @param routeCurrentNumber(已没有使用)
 */
function ownPlayRouteMap_realplay(tools, muliPoints, playTimes, colors, worker, routeCurrentNumber) {
    if (playPauseFlag) { // 当暂停时,本帧不执行
        playRouteFunction = setTimeout(function () {
            ownPlayRouteMap_realplay(tools, muliPoints, playTimes, colors, worker, routeCurrentNumber);
        }, playInterval);
        return;
    }

    var playSpeed = playInterval; // 播放速率
    var playPoints = new Array();
    var playColors = new Array();
    var playRouteCurrentNumber = new Array();
    var allOverFlag = true; // 判断是否全部播放完毕
    var playDrawFirstPoint = new Array(); // 当前帧是否需要绘制起始圆圈
    for (var i = 0; i < worker; i++) {
        var baseTime = playTimes[i]; // 基准时间
        var points = new Array();
        var mpts = muliPoints[i];
        // console.log(mpts, baseTime);
        for (var j = 0; j < mpts.length; j++) {
            if ((mpts[j].fixStart - playOffsetTime) >= baseTime.start && (mpts[j].fixStart - playOffsetTime) <= baseTime.end) {
                points.push(mpts[j]); // 由于播放基准时间playTime都是相对时间，因此当前点均需要减去素材偏移时间
            } else if ((mpts[j].fixStart - playOffsetTime) > baseTime.end) {
                break; // 当前点时间已大于本帧结束时间,则后续点必大于,因此可提前跳出循环
            }
        }

        if (baseTime.end <= (baseTime.finish)) {
            allOverFlag = false; // 只要有一个未播放完,则表示仍然需要继续播放
        }

        // console.log(points);
        if (points.length > 1) { // 只有待绘制数据点中超过2个点才绘制,因为第1个点始终是开始点
            playPoints.push(points); // 待绘制数据
            playColors.push(colors[i]); // 待绘制数据的颜色

            if (baseTime.start == 0) { // 当从本帧起始时间是0时,表示需要绘制本帧的第1个点
                playDrawFirstPoint.push(true);
            } else { // 否则,都不用绘制本帧的第1个点,这样绘制图中就不会用重复
                playDrawFirstPoint.push(false);
            }

            playRouteCurrentNumber.push(routeCurrentNumber[i]); // 当前帧中圆圈数值
            routeCurrentNumber[i] += (points.length - 1); // 设置下帧圆圈数值

            baseTime.start = (points[points.length - 1].fixStart - playOffsetTime); // 取当前数据集的最后点作为下帧开始时间
            baseTime.end += playSpeed; // 下帧结束时间增加
        } else {
            // 若本帧没有数据,则下帧起始时间不变化,下帧结束时间增加
            baseTime.end += playSpeed;
        }
    }

    if (allOverFlag) { // 全部播放完毕,则停止
        ownPlayRouteMap_stop(true);
        return;
    }

    // console.log("播放时的内容", playPoints);
    ownPlayRouteMap_progress((playProgressCurrentTime += playSpeed)); // 播放进度条

    if (playPoints.length > 0) { // 当本帧有数据要播放时
        // ownClearRoutemap();
        // addRouteCanvas();
        // routemapCanvas = $("#myCanvas");

        tools.configure({
            "element": $("#myCanvas"),
            datapoints: playPoints,
            colors: playColors,
            routeRadiusType: parseInt($("#cfg_route_radius_type").val()),
            baseRadius: parseInt($("#cfg_route_radius").val()) * displayRate,
            routeAlterableRadius: parseInt($("#cfg_route_alterable_radius").val()) * displayRate,
            routeMapDataSourceType: parseInt($("#cfg_route_data_source_type").val()),
            diaphaneity: $("#cfg_route_diaphaneity").val(),
            worker: playPoints.length, // 以本帧需播放的个数
            routeCurrentNumber: playRouteCurrentNumber,
            drawFirstPoint: playDrawFirstPoint
        });

        tools.multPlayRouteMap(); // 原playRouteMap没有使用
    }

    playRouteFunction = setTimeout(function () {
        ownPlayRouteMap_realplay(tools, muliPoints, playTimes, colors, worker, routeCurrentNumber);
    }, playInterval);
}

/**
 * 轨迹图播放及样式
 *
 * @param dataCount
 */
function ownPlayRouteMap_play(dataCount) {
    // 由于轨迹图能够播放,因此这里根据选中的项判断播放按钮是否可点击
    if (dataCount <= 0) {
        $("#playButton").unbind("click"); // 取消原绑定事件
        $("#playButton").find("i").attr("class", "icon-play-play-disabled");
        return;
    } else {
        $("#playButton").unbind("click"); // 取消原绑定事件

        // 绑定点击事件方法
        $("#playButton").bind("click", function () {
            ownPlayRouteMap_prepare();
        });
        $("#playButton").find("i").attr("class", "icon-play-play");
    }
}

/**
 * 轨迹图停止及样式
 */
function ownPlayRouteMap_stop(playFlag) {
    if (playRouteFunction != null) {
        clearTimeout(playRouteFunction);
    }
    playRouteFunction = null;

    ownPlayRouteMap_progress((playProgressCurrentTime = 0)); // 播放进度条置为0

    ownClearRoutemap();

    /** 按钮事件调整 */
    $("#playButton").unbind("click"); // 取消原绑定事件
    $("#playButton").bind("click", function () {
        ownPlayRouteMap_prepare(); // 设置成播放事件
    });
    $("#playButton").find("i").attr("class", "icon-play-play");

    $("#stopButton").unbind("click"); // 取消原绑定事件
    $("#stopButton").find("i").attr("class", "icon-play-stop-disabled");// 停止按钮不允许点击

    if (playFlag) {
        // 重新绘画
        ownDraw();
    }
}

/**
 * 轨迹图暂停及样式
 */
function ownPlayRouteMap_pause() {
    if (playPauseFlag) { // 已暂停时,则继续播放
        $("#playButton").find("i").attr("class", "icon-play-pause");
        playPauseFlag = false;
    } else { // 本来在播放,则暂停
        $("#playButton").find("i").attr("class", "icon-play-play");
        playPauseFlag = true;
    }
}

/**
 * 播放进度条计算
 *
 * @param currentTime
 */
function ownPlayRouteMap_progress() {
    if (playProgressCurrentTime >= playProgressTotalTime) {
        playProgressCurrentTime = playProgressTotalTime; // 做个显示保护:当前播放时间最大不超过播放总时间
    }
    $("#playProgress").val(Math.round((playProgressCurrentTime / 1000)) + "/" + (playProgressTotalTime / 1000) + "s"); // 显示单位:秒
    $("#progressbar").progressbar("value", (playProgressCurrentTime / playProgressTotalTime) * 100);
}

/**
 * 增加画布(焦点图、轨迹图、网格图 使用)
 */
function addMyCanvas() {
    $("#displayArea").append("<canvas id='myCanvas' ></canvas>");

    $("#myCanvas").attr("width", $("#displayArea").width());
    $("#myCanvas").attr("height", $("#displayArea").height());
    $("#myCanvas").css({
        "position": "absolute",
        "left": 0,
        "top": 0
    });
}

/**
 * 增加焦点图画布
 */
function addFocusCanvas() {
    addMyCanvas();

    var w = $("#myCanvas").width();
    var h = $("#myCanvas").height();
    var context2D = $("#myCanvas")[0].getContext("2d");
    context2D.fillStyle = "rgba(0,0,0,0.8)"; // 设置覆盖层的颜色
    context2D.fillRect(0, 0, w, h); // 设置覆盖的区域
}

/**
 * 增加轨迹图画布
 */
function addRouteCanvas() {
    addMyCanvas();
}

/**
 * 增加网格图画布
 */
function addGridCanvas() {
    addMyCanvas();

    var w = $("#myCanvas").width();
    var h = $("#myCanvas").height();
    var context2D = $("#myCanvas")[0].getContext("2d");
    context2D.fillStyle = "rgba(0,0,0,0.2)"; // 设置覆盖层的颜色
    context2D.fillRect(0, 0, w, h); // 设置覆盖的区域
}

/**
 * 增加兴趣区画布
 */
function addAoiCanvas() {
    addMyCanvas();
}

/**
 * 加载方案信息
 */
function loadScheme(schemeJson) {
    schemeWidth = schemeJson.Width;
    schemeHeight = schemeJson.Height;
    // 如果未加载素材,则默认加载方案的第一个素材
    var materialCode = $("#materialCode").val();
    if (materialCode == null || materialCode == "") {
        $("#materialCode").val(schemeJson.Materials[0].Code);
    }
}

/**
 * 加载AOI信息
 */
function loadAoiGraphs() {
    schemeAoiGraphs = eval('(' + $("#schemeAoiGraphs").val() + ')'); // AOI兴趣区信息(当前是和方案关联)
    for (var i = 0; i < schemeAoiGraphs.length; i++) {
        // 将后台已保存的AOI图形，放入已绘制的数组中，便于后续一次保存（后台与页面交互时，不会判断哪些AOI被删除了，只会全量保存）
        if (schemeAoiGraphs[i].type == AoiTypeEnum.POLYGON) {
            aoiGraphs_temp.push({
                type: schemeAoiGraphs[i].type,
                name: schemeAoiGraphs[i].name,
                showName: schemeAoiGraphs[i].showName,
                status: true,
                poLength: schemeAoiGraphs[i].poLength
            });
        } else {
            aoiGraphs_temp.push({
                type: schemeAoiGraphs[i].type,
                name: schemeAoiGraphs[i].name,
                showName: schemeAoiGraphs[i].showName,
                status: true,
                poLength: 0
            });
        }
    }
}

/**
 * 选择素材回调函数
 */
function selectMaterialHook(material) {
    var inputPara = {
        "projectCode": $("#projectCode").val(),
        "schemeCode": $("#schemeCode").val(),
        "materialCode": material.code
    };

    $("#materialCode").val(material.code);
    $("#materialType").val(material.type);

    var url = "";

    if ($("#materialType").val() == MaterialTypeEnum.RECORD) { // 素材类型是录制
        url = "analysis_loadMaterialAndData.action"; // 需要注视点数据和原始数据
    } else { // 其它类型,不一定需要原始数据
        if ($("#analysisType").val() == AnalysisTypeEnum.ROUTEMAP) { // 轨迹图需要注视点数据和原始数据
            url = "analysis_loadMaterialAndData.action";

        } else { // 热点图、轨迹图、焦点
            url = "analysis_loadMaterialAndFixationData.action";
        }
    }
    loading();
    initRightMenu(); // 根据素材类型加载鼠标右击菜单
    callJsonDataWithMethod(url, inputPara, loadMaterialAndResult, loadErrorFunction);
}

/**
 * 加载素材信息&被试数据
 */
function loadMaterialAndResult(retListJson) {
    var rt1 = retListJson[0], rt2 = retListJson[1];
    var minDuration = rt1.Duration;
    loadMaterial(rt1, getDurationMax(rt2, minDuration));
    loadResultAndData(rt2, minDuration);
    calcRelativeData();
    closeLoad();
    ownDrawByAlreadyCheckboxs();
}

/**
 * 获取最大时间间隔
 *
 * @param data
 */
function getDurationMax(data, minDuration) {
    // 获取当前已经选中的checkbox值
    var box = getAlreadyValue();
    if (box) {
        //获取最后的结果集
        var dts = box.split('_').map(function (b) {
            return parseInt(data[b].Duration || minDuration);
        });
        return dts.sort()[dts.length - 1];
    }
}

/**
 * 加载素材信息
 */
function loadMaterial(materialJson, maxDuration) {
    // 根据素材类型加载对应的素材
    clearDisplayArea();
    $("#mainVideo").hide();
    $("#mainImage").hide();
    if ($("#materialType").val() == MaterialTypeEnum.IMAGE) { // 素材类型是图片
        var imageUrl = "image_show.action?projectCode=" + $("#projectCode").val() + "&schemeCode=" + $("#schemeCode").val() + "&materialCode=" + materialJson.Code + "&materialSuffix="
            + materialJson.Suffix;
        $("#mainImage").attr("src", imageUrl);

        $("#mainImage").show();

    } else if ($("#materialType").val() == MaterialTypeEnum.VIDEO) { // 素材类型是视频
        var videoUrl = "image_show.action?projectCode=" + $("#projectCode").val() + "&schemeCode=" + $("#schemeCode").val() + "&materialCode=" + materialJson.Code + "&materialSuffix="
            + materialJson.Suffix;

        // poster在接口定义中默认格式是jpg
        var posterUrl = "image_show.action?projectCode=" + $("#projectCode").val() + "&schemeCode=" + $("#schemeCode").val() + "&materialCode=" + materialJson.Code + "&materialSuffix="
            + VIDEO_POSTER_SUFFIX;

        $("#mainVideo").attr("src", videoUrl);
        $("#mainVideo").attr("poster", posterUrl);
        // $("#mainVideo").attr("autoplay", "autoplay");

        $("#mainVideo").show();
    } else if ($("#materialType").val() == MaterialTypeEnum.RECORD) { // 素材类型是录制
        $("#mainVideo").attr("src", "");
        $("#mainVideo").show();
    }

    materialWidth = materialJson.Width;
    materialHeight = materialJson.Height;

    playProgressTotalTime = maxDuration || materialJson.Duration; // 播放进度总时间

    playOffsetTime = materialJson.Offset; // 素材播放偏移时间
    ownPlayRouteMap_progress((playProgressCurrentTime = 0)); // 播放进度条置为0
    changeProgressbar();

    configListSet(); // 参数选择区域
    playAreaSet(); // 切换素材后需要判断播放区域
    aoiAreaSet(); // 切换素材后需要判断兴趣区域
}

/**
 * 加载被试及数据
 */
function loadResultAndData(resultDataJson, minDuration) {
    if (resultDataJson != null) { // 当返回的结果列表时null时,做个保护
        var htmlContent = "";
        var type = $("#analysisType").val();

        for (var i = 0; i < resultDataJson.length; i++) {
            var checkName = resultDataJson[i].name;
            htmlContent += "<tr id='result_checkbox_row" + i + "'><td>";
            if (getAnalysisRadio()) {
                htmlContent += "<input type='radio' class='analysis-type-item' name='analysisRadio' value='" + i + "' data-name='" + checkName + "'/>";
            } else {
                htmlContent += "<input type='checkbox' class='analysis-type-item' value='" + i + "' data-name='" + checkName + "'/>";
            }
            htmlContent += checkName + "</td>";
            if (type !== AnalysisTypeEnum.HEATMAP && type !== AnalysisTypeEnum.FOCUSMAP && type !== AnalysisTypeEnum.GRIDMAP) {
                // 热点图、焦点图、网格图不显示颜色
                htmlContent += "<td><span class='colors c" + (i % 10) + "' ><em></em></span></td>"; // 目前10个颜色,故取10的余数
            }
            htmlContent += "</tr>";
        }
        $("#resultBody").html(htmlContent);

        resultDataList = resultDataJson;

        // 增加onclick方法:选择被试后立即进行渲染
        getAlreadyCheck().change(function () {
            saveAlreadyCheckboxs($(this));

            // 设置播放时长
            playProgressTotalTime = getDurationMax(resultDataList, minDuration);
            ownPlayRouteMap_progress((playProgressCurrentTime = 0)); // 播放进度条置为0
            changeProgressbar();

            ownDraw();
        });

        loadResultCheckboxRowTooltip();
    }
    // checkbox列表行选择样式和勾选
    initDatagrid();
    initDatagrid_click();

    // 重新调整高度
    sliderH();
}

/**
 * 改变参数时重新绘制
 */
function changeConfig2Draw() {
    var type = $("#analysisType").val();
    if (type == AnalysisTypeEnum.AOI) {
        changeAoiDrawColorStyle();
        return; // AOI改变参数时，由于参数的作用只是绘制编辑AOI图形，因此不用重新统计
    }
    configListSet();
    playAreaSet();
    aoiAreaSet();
    sliderH();

    ownDraw();
}

/**
 * 通过缩放比计算原始被试数据
 */
function calcRelativeData() {
    for (var i = 0; i < resultDataList.length; i++) {
        if (resultDataList[i].fixData != null) {
            for (var j = 0; j < resultDataList[i].fixData.length; j++) {
                resultDataList[i].fixData[j].x = resultDataList[i].fixData[j].x * displayRate;
                resultDataList[i].fixData[j].y = resultDataList[i].fixData[j].y * displayRate;
            }
        }
    }

    for (var i = 0; i < resultDataList.length; i++) {
        if (resultDataList[i].rawData != null) {
            for (var j = 0; j < resultDataList[i].rawData.length; j++) {
                resultDataList[i].rawData[j].x = resultDataList[i].rawData[j].x * displayRate;
                resultDataList[i].rawData[j].y = resultDataList[i].rawData[j].y * displayRate;
            }
        }
    }

}

/**
 * 调整展示区宽度、高度、样式
 */
function sliderH() {
    // 绘制参数增加样式
    $("#configList").find("select").each(function () {
        $(this).addClass("select_min");
    });

    var analysisType = $("#analysisType").val();

    if (analysisType === AnalysisTypeEnum.STATISTIC) {
        return;
    }

    // 计算左侧结果选择区域高度
    var hh = $("#col-main").height(), testObjectH = $("#testObject").outerHeight(true);
    var cfgHeight = $("#configList").height();
    $("#dataList").height(hh - testObjectH - cfgHeight - 10); // 设置左侧颜色列表高度,减1是为了不显示竖滚动条

    // 需要重新布置面板画布，防止出现特殊现象
    var widget = $('#widget');
    var wgWidth = widget.width();
    var wgHeight = widget.height();
    // 设置区域大小并实现居中
    var offset = 10;
    var areaWidth = wgWidth - offset;
    var areaHeight = wgHeight - offset;

    // 计算当前展示图片的大小，检查并计算缩放程度
    displayRate = calcRate(schemeWidth, schemeHeight, areaWidth, areaHeight); // 展示区相当于方案屏幕分辨率的缩放比

    /** 计算展示区画布大小和位置 */
    var daWidth = schemeWidth * displayRate; // 图片需要先按屏幕缩放比计算,再计算放置到展示区中
    var daHeight = schemeHeight * displayRate;

    var oLeft = (wgWidth - daWidth) / 2;
    var oTop = (wgHeight - daHeight) / 2;
    $("#displayArea").css({
        "height": daHeight,
        "width": daWidth,
        "position": "relative",
        "left": oLeft,
        "top": oTop
    });

    /** 计算展示区图片大小和位置 */
    var imageWidth = materialWidth * displayRate; // 图片需要先按屏幕缩放比计算,再计算放置到展示区中
    var imageHeight = materialHeight * displayRate;

    var rateImg = calcRate(imageWidth, imageHeight, daWidth, daHeight); // 图片与展示区的缩放比
    rateImg = rateImg > 1 ? 1 : rateImg;

    var iWidth = imageWidth * rateImg;
    var iHeight = imageHeight * rateImg;
    var iTop = (daHeight - iHeight) / 2;

    var materialType = $("#materialType").val();
    if (materialType == MaterialTypeEnum.IMAGE) { // 素材类型是图片
        $("#mainImage").css({
            "height": iHeight,
            "width": iWidth,
            "position": "relative",
            "top": iTop
        });
    } else if (materialType == MaterialTypeEnum.VIDEO
        || materialType == MaterialTypeEnum.RECORD) { // 素材类型是视频 + 素材类型是录制
        // 视频素材的宽度和高度仍然根据素材来
        $("#mainVideo").css({
            "height": iHeight,
            "width": iWidth,
            "position": "relative",
            "top": iTop
        });
    }

    /** 设置颜色示例条位置,与展示区宽度相同 */
    $("#color_example").css({
        "position": "absolute",
        "left": $("#displayArea").offset().left,
        "width": $("#displayArea").width()
    });

    /** tbody高度必须要小于父div(dataList)高度 */
    if ($("#resultBody").height() > $("#dataList").height()) {
        $("#resultBody").height($("#dataList").height());
    }
}

/**
 * 绑定浮动显示项
 */
function bindTopic() {
    var myElement = document.getElementById('displayArea'); // 浮动显示区域为绘图区

    myElement.onmouseout = function () { // 鼠标移除不再显示
        hideTopic();
    };
    myElement.onmousemove = function (ev) { // 鼠标移动计算是否显示
        var oEvent = window.event || ev;

        var content = calcTopic(oEvent);
        if (content == null) { // 当显示内容不为空时显示
            hideTopic();
        } else {
            showTopic(content, oEvent);
        }

    };
}

/**
 * 计算浮动显示内容
 *
 * @param oEvent
 * @returns
 */
function calcTopic(oEvent) {
    var left = $("#displayArea").offset().left;
    var top = $("#displayArea").offset().top;

    var x = oEvent.clientX - left; // 相对绘图区域x坐标
    var y = oEvent.clientY - top; // 相对绘图区域y坐标

    var content = null;
    if ($("#analysisType").val() == AnalysisTypeEnum.GRIDMAP) {
        content = calcTopicByGridmap(x, y);
        if (content == null) { // 这里再更加content做个右击菜单的更新，当在Map图形内时，可以进行Map导出等右击菜单的更新
            initRightMenu(); // 等于空表示没有在Map图形内，返回原右击菜单
        } else {
            reInitRightMenuByMap(); // 不等于空表示在Map图形内,则加载AOI的右击菜单
        }
    } else if ($("#analysisType").val() == AnalysisTypeEnum.AOI) {
        content = calcTopicByAoi(x, y);
        if (content == null) { // 这里再更加content做个右击菜单的更新，当在AOI图形内时，可以进行AOI编辑、导出等右击菜单的更新
            initRightMenu2(); // 等于空表示没有在AOI图形内，返回原右击菜单
        } else {
            reInitRightMenuByAoi(); // 不等于空表示在AOI图形内,则加载AOI的右击菜单
        }
    }
    return content;
}

/**
 * 计算浮动显示内容(网格图)
 *
 * @param x
 * @param y
 * @returns
 */
function calcTopicByGridmap(x, y) {
    var perWidth = $("#displayArea").width() / parseInt($("#cfg_grid_row").val()); // 每网格宽度
    var perHeight = $("#displayArea").height() / parseInt($("#cfg_grid_column").val()); // 每网格高度

    var dataX = Math.floor(x / perWidth);
    var dataY = Math.floor(y / perHeight);

    try {
        selectGridMapKey = '';
        if (gridmapDataList != null && gridmapDataList[dataX][dataY].duration > 0) {
            selectGridMapKey = dataX + '_' + dataY;
            var msg = "<table><colgroup><col width='120' /><col /></colgroup><tbody>";
            msg += "<tr><td>持续时长</td><td>" + gridmapDataList[dataX][dataY].duration + "ms</td></tr>";
            msg += "<tr><td>注视点个数</td><td>" + gridmapDataList[dataX][dataY].fixCount + "</td></tr>";
            msg += "<tr><td>首次进入时间</td><td>" + gridmapDataList[dataX][dataY].firstStart + "ms</td></tr>";
            msg += "<tr><td>结果命中数</td><td>" + gridmapDataList[dataX][dataY].hitCount + "</td></tr>";
            msg += "<tr><td>结果命中率</td><td>" + gridmapDataList[dataX][dataY].hitCountRatio + "%</td></tr>";
            msg += "<tr><td>平均持续时长</td><td>" + gridmapDataList[dataX][dataY].durationAvg + "ms</td></tr>";
            msg += "<tr><td>左眼瞳孔平均</td><td>" + gridmapDataList[dataX][dataY].leftPupilSize + "</td></tr>";
            msg += "<tr><td>右眼瞳孔平均</td><td>" + gridmapDataList[dataX][dataY].rightPupilSize + "</td></tr>";
            msg += "</tbody></table>";
            return msg;
        } else {
            return null;
        }
    } catch (e) {
        // 做个异常保护,返回空
        return null;
    }
}

/**
 * 计算浮动显示内容(兴趣区)
 *
 * @param x
 * @param y
 * @returns
 */
function calcTopicByAoi(x, y) {
    try {
        if (aoiDataList == null || aoiDataList.length <= 0) {
            return null;// 如果兴趣区数据集是空，则代表没有选择结果，不用绘制
        }
        var graphs = schemeAoiGraphs;
        var canvasId = "myCanvas";
        for (var p = 0; p < graphs.length; p++) {
            var widthRate = graphs[p].canvasWidth / $("#" + canvasId).width(); // 画布宽的缩放比
            var heightRate = graphs[p].canvasHeight / $("#" + canvasId).height(); // 画布高的缩放比
            var mPoints = new Array(); // 多边形的顶点集合
            if (graphs[p].type == AoiTypeEnum.POLYGON) {
                for (var k = 0; k < graphs[p].poLength; k++) {
                    mPoints.push({
                        x: graphs[p].points[k].x + graphs[p].x,
                        y: graphs[p].points[k].y + graphs[p].y
                    }); // 多边形所有图形，在拖动时只会变化x和y坐标，因此绘制、计算时需要与x和y坐标相加
                }
            }

            var isContain = false;
            if (graphs[p].type == AoiTypeEnum.RECTANGLE) {
                isContain = isRectangleContainsPoint(graphs[p].x, graphs[p].y, graphs[p].width, graphs[p].height, {
                    x: x * widthRate,
                    y: y * heightRate
                });
            } else if (graphs[p].type == AoiTypeEnum.ELLIPSE) {
                // graphs中的x和y是左上角的坐标，因此需要换算到圆形中心坐标
                isContain = isEllipseContainsPoint(graphs[p].x + graphs[p].width / 2, graphs[p].y + graphs[p].height / 2, graphs[p].width, graphs[p].height, {
                    x: x * widthRate,
                    y: y * heightRate
                });
            } else if (graphs[p].type == AoiTypeEnum.POLYGON) {
                isContain = isPolygonContainsPoint(mPoints, {
                    x: x * widthRate,
                    y: y * heightRate
                });
            }
            if (isContain) {
                var aoiGraph = aoiDataList[p]; // 数据集的顺序和AOI图形的顺序是一样的，因此可以直接根据参数p定位
                modifyAoiIndex = p; // 对当前待编辑的菜单赋值
                var msg_temp = "";
                var msg = "<table><colgroup><col width='120' /><col /></colgroup><tbody>";
                msg += "<tr><td colspan='2' align='center' ><font size='2'><b>" + schemeAoiGraphs[p].showName + "</b></font></td></tr>";
                msg += "<tr><td>持续时长</td><td>" + aoiGraph.data.duration + "ms</td></tr>";
                msg += "<tr><td>注视点个数</td><td>" + aoiGraph.data.fixCount + "</td></tr>";

                if (aoiGraph.data.firstStart == null) {
                    msg_temp = "N/A";
                } else {
                    msg_temp = aoiGraph.data.firstStart + "ms";
                }
                msg += "<tr><td>首次进入时间</td><td>" + msg_temp + "</td></tr>";

                msg += "<tr><td>结果命中数</td><td>" + aoiGraph.data.hitCount + "</td></tr>";
                msg += "<tr><td>结果命中率</td><td>" + aoiGraph.data.hitCountRatio + "%</td></tr>";

                if (isNaN(aoiGraph.data.durationAvg)) {
                    msg_temp = "0";
                } else {
                    msg_temp = aoiGraph.data.durationAvg;
                }
                msg += "<tr><td>平均持续时长</td><td>" + msg_temp + "ms</td></tr>";

                if (isNaN(aoiGraph.data.leftPupilSize)) {
                    msg_temp = "N/A";
                } else {
                    msg_temp = aoiGraph.data.leftPupilSize;
                }
                msg += "<tr><td>左眼瞳孔平均</td><td>" + msg_temp + "</td></tr>";

                if (isNaN(aoiGraph.data.rightPupilSize)) {
                    msg_temp = "N/A";
                } else {
                    msg_temp = aoiGraph.data.rightPupilSize;
                }
                msg += "<tr><td>右眼瞳孔平均</td><td>" + msg_temp + "</td></tr>";
                msg += "</tbody></table>";
                return msg;
            }
        }
        return null;
    } catch (e) {
        // 做个异常保护,返回空
        return null;
    }
}

/**
 * 绑定参数的解释
 */
function bindConfigExplain() {
    // tip提示信息
    $(".tipTarget").bt({
        trigger: 'hover',
        contentSelector: "$(this).next('.tip').html()",
        width: 300,
        fill: 'rgba(246, 255, 237,0.95)',
        strokeWidth: 1,
        strokeStyle: '#72aa39',
        spikeLength: 10,
        spikeGirth: 10,
        padding: 20,
        cornerRadius: 5
    });
}

/**
 * 导出报告
 * @param
 */
function report(data){
    let projectCode = $("#projectCode").val();
    let schemeCode = $("#schemeCode").val();
    let url = "analysis_popReportAoi.action?projectCode=" + projectCode + "&schemeCode=" + schemeCode ;
    let results = getAlreadyCheck(true);
    let resultName = {};
    if(results && results.length >0){
        resultName = {name:results[0].dataset.name};
        resultName = encodeURI(JSON.stringify(resultName));
        url = url + "&resultName="+encodeURIComponent(resultName,'utf-8');
    }
    let jsonData = [];
    if (data && data.length > 0 ){
        for (i = 0 ;i<data.length;i++){
            jsonData.push({name:data[i].name,data:data[i].data});
        }
        url = url + "&aoiData= "+encodeURIComponent(JSON.stringify(jsonData),'utf-8');
    }

    popup('眼动检查分析报告数据', url, 400, 420, 'reportAoi', true);
}


/**
 *非AOI区域新增一个右键菜单
 * 保存图片
 * 导出报告
 */
function initRightMenu2() {
    $("#displayArea").smartMenu(); // 先清除按钮

    if ($("#materialType").val() == MaterialTypeEnum.RECORD) { // 素材类型是录制,不能保存图片
        return;
    }

    var imageMenuData = [[{
        text: "保存图片",
        func: function () {
            setTimeout(function () {
                cropImage();
            }, 10); // 通过延迟异步打开下载截图内容
        }
    },{
        text: "导出报表",
        func: function () {
            setTimeout(function () {
                report(aoiDataList);
            }, 10); // 通过延迟异步打开下载截图内容
        }
    }]];

    $("#displayArea").smartMenu(imageMenuData, {
        name: "image2"
    });
}

/**
 * 初始鼠标右键菜单
 */
function initRightMenu() {
    $("#displayArea").smartMenu(); // 先清除按钮

    if ($("#materialType").val() == MaterialTypeEnum.RECORD) { // 素材类型是录制,不能保存图片
        return;
    }

    var imageMenuData = [[{
        text: "保存图片",
        func: function () {
            setTimeout(function () {
                cropImage();
            }, 10); // 通过延迟异步打开下载截图内容
        }
    }]];

    $("#displayArea").smartMenu(imageMenuData, {
        name: "image"
    });
}

/**
 * 当进入AOI兴趣区时,重新初始鼠标右键菜单
 */
function reInitRightMenuByAoi() {
    $("#displayArea").smartMenu(); // 先清除按钮

    var imageMenuData = [[{
        text: "修改&导出",
        func: function () {
            setTimeout(function () {
                modifyAoi(modifyAoiIndex);
            }, 10); // 通过延迟异步打开弹出框内容
        }
    }]];
    $("#displayArea").smartMenu(imageMenuData, {
        name: "aoiMenu"
    });
}

/**
 * 网格区的邮件功能，数据导出
 */
function reInitRightMenuByMap() {
    $("#displayArea").smartMenu(); // 先清除按钮

    var imageMenuData = [[{
        text: "导出数据",
        func: function () {
            setTimeout(function () {
                exportMapGraphs();
            }, 10); // 通过延迟异步打开弹出框内容
        }
    }]];
    $("#displayArea").smartMenu(imageMenuData, {
        name: "mapMenu"
    });
}

/**
 * 初始测评结果区域的鼠标右键菜单
 */
function initDataListRightMenu() {
    var imageMenuData = [[{
        text: "全选",
        func: function () {
            if ($("#materialType").val() == MaterialTypeEnum.RECORD) { // 素材类型是录制，不允许全选
                popalert({
                    "content": "录制类型,不允许全选！",
                    "icon": "warning",
                    "okVal": "确定",
                    "cancel": false
                });
            } else {
                ownSelectAllAndDraw();
            }
        }
    }, {
        text: "取消全选",
        func: function () {
            ownClear();
        }
    }], [{
        text: "修改",
        func: function () {
            modifyResult();
        }
    }]];

    $("#resultBody").smartMenu(imageMenuData, {
        name: "image_resultBody"
    });
}

/**
 * 弹出修改被试信息窗口
 */
function modifyResult() {
    var projectCode = $("#projectCode").val();
    var schemeCode = $("#schemeCode").val();
    var url = "analysis_popModifyResult.action?projectCode=" + projectCode + "&schemeCode=" + schemeCode;

    popup('修改被试信息', url, 650, 500, 'modifyResult', true);
}

/**
 * 修改被试信息函数
 */
function modifyResultHook() {
    var type = $("#analysisType").val(); // 获取当前正在分析的类型
    loadAnalysis(type); // 刷新整个页面
}

/**
 * 弹出修改AOI信息窗口
 */
function modifyAoi(modifyAoiIndex) {
    var projectCode = $("#projectCode").val();
    var schemeCode = $("#schemeCode").val();
    var url = "analysis_popModifyAoi.action?projectCode=" + projectCode + "&schemeCode=" + schemeCode + "&modifyAoiIndex=" + modifyAoiIndex;

    popup('兴趣区信息', url, 400, 250, 'modifyAoi', true);
}

/**
 * 清除视频区域播放
 */
function clearDisplayArea() {
    // 视频清除
    $("#mainVideo").get(0).pause();
    $("#mainVideo").removeAttr("src");
    $("#mainVideo").removeAttr("poster");
    $("#mainVideo").removeAttr("preload");
    $("#mainVideo").removeAttr("type");
    $("#mainVideo").unbind("canplaythrough");
    $("#mainVideo").unbind("canplay");

    // 图片清除
    $("#mainImage").removeAttr("src");
}


/**
 * 导出网格图数据
 */
function exportMapGraphs() {
    /** 准备待导出的数据集 */
    var objs = [];
    if (selectGridMapKey) {
        var keys = selectGridMapKey.split('_');
        var i = Number(keys[0]);
        var j = Number(keys[1]);
        objs = gridmapDataList[i][j].store;
    }
    // 导出选中的数据内容
    var retStr = "data:text/csv;charset=utf-8,\ufeff";
    retStr += "结果名,开始时间[ms],持续时间[ms],结束时间[ms],X位置[px],Y位置[px],左眼瞳孔平均值,右眼瞳孔平均值,\r\n";
    if (objs && objs.length > 0) {
        var split = ",";
        objs.forEach(function (o) {
            // 格式化导出数据成csv格式
            retStr += o.base.name + split;
            retStr += o.fixStart + split + o.fixDur + split + (o.fixStart + o.fixDur) + split;
            retStr += +Math.floor(o.x * 100) / 100 + split + Math.floor(o.y * 100) / 100 + split + o.LPS + split + o.RPS + split + "\r\n";
        });
    }

    /** 导出的数据集 */
    var encodedUri = encodeURI(retStr);
    var save_link = document.createElement("a");
    save_link.setAttribute("href", encodedUri);
    var filename = (new Date()).getTime() + '.csv'; // 文件名
    save_link.setAttribute("download", filename);

    document.body.appendChild(save_link);

    // save_link.click(); //该方式在客户端嵌入时无法导出
    var event = document.createEvent('MouseEvents');
    event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    save_link.dispatchEvent(event);
}

/**
 * 获取被选中的数据集
 */
function getAlreadyCheckValue(key) {
    var boxArray = getAlreadyCheck(true);
    var objs = new Array(); // 所有选择的被试数据
    for (var i = 0; i < boxArray.length; i++) {
        objs.push(resultDataList[boxArray.eq(i).val()][key]);
    }
    return {
        works: boxArray,
        data: objs,
    };
}
